<?php
/**
 * tmaic.com 
 * ============================================================================
 * * 版权所有 2020-2030 tmaic，并保留所有权利。
 * 网站地址: http://www.tmaic.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: pangxianfei
 * $email:421339244@qq.com
 * $phone:18929142226
 * $date 2020-11-13
*/
namespace App\Http\Controllers\Admin;

use App\Http\Requests\PermissionCreateRequest;
use App\Http\Requests\PermissionUpdateRequest;
use Illuminate\Http\Request;
use App\Http\Controllers\AdminController;
use App\Models\Permissions\Permissions as Permissions;
use App\Models\Permission as Permission;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Response;

class PermissionController extends AdminController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        
        return view('admin.permission.index');
    }

    /**
     * 数据接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function data(Request $request)
    {


        $pid = $request->pid??0;
        $created_at = $request->created_at??null;
        $lang = $request->get('lang','zh');
        $model = Permission::query();
        $res =$model->with('children')->where('parent_id',0)->orderBy('sort','asc')->get();
        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $res->count(),
            'data'  => $res
        ];
        return Response::json($data);
    }


    /**
     * 后台菜单数据接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function menuData(Request $request)
    {
        $pid = $request->id??0;
 
        $model = Permission::query();

        if($pid){
           $model = $model->where('id',$pid);
        }else{

          $model = $model->where('parent_id',$pid);
        }

         $res = $model->with([
                'childs' => function ($query) {
                    return $query->with('icon');
                }, 'icon'])->where('status',1)->orderBy('sort', 'asc')->get();

        $menuData=[];
        foreach($res as $key=>$item){
            $menuData[$key]['name']=$item->display_name;
            $menuData[$key]['url']=$item->route?route($item->route):'';  
            $menuData[$key]['icon']=$item->icon->class?"layui-icon ".$item->icon->class:'';  
    
            if(count($item->children)){
                foreach($item->children as $subkey=>$nav){
                    $menuData[$key]['subMenus'][$subkey]['name']=$nav->display_name;
                    $menuData[$key]['subMenus'][$subkey]['url']=$nav->route?route($nav->route):'';                 
                }
            }

        }
        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' =>count($menuData),
            'data'  => $menuData
        ];
        return Response::json($data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $permissions = $this->tree();
        return view('admin.permission.create',compact('permissions'));
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(PermissionCreateRequest $request)
    {
         $data = $request->all();

        if (Permission::create($data)){
            return Response::json(['code'=>0,'msg'=>'添加成功']);
        }
        return Response::json(['code'=>0,'msg'=>'添加成功']);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $request)
    {
        $id = $request->id;
        $permission = Permission::findOrFail($id);
        $permissions = $this->tree();
        return view('admin.permission.edit',compact('permission','permissions'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $id = $request->id;
        $permission = Permission::findOrFail($id);
        $data = $request->all();

        if ($permission->update($data)){
            return Response::json(['code'=>0,'msg'=>'更新权限成功']);
        }
        return Response::json(['code'=>1,'msg'=>'系统错误']);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function updateAjax(Request $request)
    {
        $id = $request->id;
        $status = $request->status;
        $permission = Permission::findOrFail($id);

        DB::beginTransaction();
        if ($permission){
            //$reslut = DB::table('permissions')->where('id', $id)->update(['status'=>$status]);
            $reslut = $permission->where('id',$id)->update(['status'=>$status]);
            DB::commit();
            return Response::json(['code'=>0,'msg'=>'更新权限成功']);
        }
        DB::rollback();
        return Response::json(['code'=>1,'msg'=>'系统错误']);
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $id = $request->get('ids');
        if (empty($ids)){
            return response()->json(['code'=>1,'msg'=>'请选择删除项']);
        }
        DB::beginTransaction();
        $permission = Permissions::find($id);
        if (!$permission){
            return response()->json(['code'=>-1,'msg'=>'权限不存在']);
        }
        //如果有子权限，则禁止删除
        if (Permissions::where('parent_id',$id)->first()){

            return response()->json(['code'=>2,'msg'=>'存在子权限禁止删除']);
        }

        if ($permission->delete()){
            DB::commit();
            return response()->json(['code'=>0,'msg'=>'删除成功']);
        }
        DB::rollback();
        return response()->json(['code'=>1,'msg'=>'删除失败']);
    }
}
